package wnhz.com.business.groupshop.ui;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import butterknife.BindView;
import butterknife.ButterKnife;
import wnhz.com.business.R;
import wnhz.com.business.base.BaseActivity;
import wnhz.com.business.groupshop.bean.AddressInfo;
import wnhz.com.business.constants.Constants;
import wnhz.com.business.impl.ActionBarClickListener;
import wnhz.com.business.uitls.pickerDialog.CityPickerPopWindow;
import wnhz.com.business.uitls.Base64Util;
import wnhz.com.business.uitls.BroadCastReceiverUtil;
import wnhz.com.business.uitls.FastUtils;
import wnhz.com.business.uitls.LogUtils;
import wnhz.com.business.uitls.MyCallBack;
import wnhz.com.business.uitls.ToastUtils;
import wnhz.com.business.uitls.Url;
import wnhz.com.business.uitls.XUtil;
import wnhz.com.business.view.TranslucentActionBar;

public class EditAddressActivity extends BaseActivity implements View.OnClickListener, ActionBarClickListener, CityPickerPopWindow.CityPickListener {

    @BindView(R.id.root_layout)
    LinearLayout root_layout;
    @BindView(R.id.edit_consignee)
    EditText edit_consignee;
    @BindView(R.id.edit_phone)
    EditText edit_phone;
    @BindView(R.id.text_address)
    TextView text_address;
    @BindView(R.id.edit_detail)
    EditText edit_detail;
    @BindView(R.id.iv_lianxiren)
    ImageView iv_lianxiren;
    @BindView(R.id.ll_address)
    LinearLayout ll_address;
//    @BindView(R.id.edit_code)
//    EditText edit_code;
    @BindView(R.id.btn_home)
    RadioButton btn_home;
    @BindView(R.id.btn_company)
    RadioButton btn_company;
    @BindView(R.id.btn_def_address)
    CheckBox btn_def_address;
    @BindView(R.id.actionbar)
    TranslucentActionBar actionbar;

    @BindView(R.id.ll_def_address)
    LinearLayout ll_def_address;

    @BindView(R.id.ll_home)
    LinearLayout ll_home;

    @BindView(R.id.ll_company)
    LinearLayout ll_company;

    private String province, city, district;
    private int addressType = 1;
    private int isDefault = 2;
    private AddressInfo.InfoBean infoBean;
    private boolean flag = false;

    public static Intent createIntent(Context context, AddressInfo.InfoBean infoBean) {
        Intent intent = new Intent(context, EditAddressActivity.class);
        Bundle bundle = new Bundle();
        bundle.putSerializable("infoBean", infoBean);
        intent.putExtras(bundle);
        return intent;
    }

    public void parseIntent() {
        Intent intent = getIntent();
        infoBean = (AddressInfo.InfoBean) intent.getSerializableExtra("infoBean");
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_edit_address);
        ButterKnife.bind(this);
        parseIntent();
        actionbar.setData("编辑地址", R.drawable.ic_lefft_white, null, 0, "保存",0, this);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            this.getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            actionbar.setStatusBarHeight(getStatusBarHeight());
        }
        setData();
        initView();
    }

    private void setData() {
        edit_consignee.setText(infoBean.getConsignee());

        edit_phone.setText(infoBean.getTelephone());

        text_address.setText(infoBean.getProvince() + "-" + infoBean.getCity() + "-" + infoBean.getAddress());

        edit_detail.setText(infoBean.getPlace());

//        edit_code.setText(infoBean.getDoorplate());
if(null!=infoBean.getAddressType()){
    if (infoBean.getAddressType().equals("1")) {
        btn_home.setChecked(true);
    } else {
        btn_company.setChecked(true);

    }
}

        if (infoBean.getMoren().equals("1")) {
            btn_def_address.setChecked(true);
            flag = true;
            isDefault = 1;
        } else {
            btn_def_address.setChecked(false);
            flag = false;
        }
    }

    private void initView() {
        iv_lianxiren.setOnClickListener(this);
        ll_home.setOnClickListener(this);
        ll_company.setOnClickListener(this);
        ll_def_address.setOnClickListener(this);
        ll_address.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_lianxiren:
                Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
                EditAddressActivity.this.startActivityForResult(intent, 1);
                break;
            case R.id.ll_address:
                if (!FastUtils.isFastDoubleClick()) {
                    //判断软键盘是否打开，为true则关闭，否则不处理
                    InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                    boolean isOpen = imm.isActive();
                    if (isOpen) {
                        closrKeyboard();
                    }

                    //城市选择弹出框
                    CityPickerPopWindow mPopWindow = new CityPickerPopWindow(this);
                    mPopWindow.showPopupWindow(root_layout);
                    mPopWindow.setCityPickListener(this);
                }
                break;
            case R.id.ll_home:
                btn_home.setChecked(true);
                btn_company.setChecked(false);
                addressType = 1;
                break;
            case R.id.ll_company:
                btn_home.setChecked(false);
                btn_company.setChecked(true);
                addressType = 2;
                break;
            case R.id.ll_def_address:
                if (!flag) {
                    btn_def_address.setChecked(true);
                    isDefault = 1;
                    flag = true;
                    LogUtils.e("==设置默认地址  默认==", isDefault + "");
                } else {
                    btn_def_address.setChecked(false);
                    isDefault = 2;
                    flag = false;
                    LogUtils.e("==设置默认地址  不默认==", isDefault + "");
                }
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // TODO Auto-generated method stub
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case (1): {
                if (resultCode == Activity.RESULT_OK) {
                    Uri contactData = data.getData();
                    Cursor c = managedQuery(contactData, null, null, null, null);
                    c.moveToFirst();
                    String phoneNum = this.getContactPhone(c);
                    edit_phone.setText(phoneNum);
                }
                break;
            }

        }
    }

    //获取联系人电话号码
    private String getContactPhone(Cursor cursor) {
        int phoneColumn = cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER);
        int phoneNum = cursor.getInt(phoneColumn);
        String phoneResult = "";
        if (phoneNum > 0) {
            // 获得联系人的ID号
            int idColumn = cursor.getColumnIndex(ContactsContract.Contacts._ID);
            String contactId = cursor.getString(idColumn);
            // 获得联系人的电话号码的cursor;
            Cursor phones = getContentResolver().query(
                    ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                    null,
                    ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = " + contactId,
                    null, null);
            if (phones.moveToFirst()) {
                // 遍历所有的电话号码
                for (; !phones.isAfterLast(); phones.moveToNext()) {
                    int index = phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
                    int typeindex = phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.TYPE);
                    int phone_type = phones.getInt(typeindex);
                    String phoneNumber = phones.getString(index);
                    switch (phone_type) {
                        case 2:
                            phoneResult = phoneNumber;
                            break;
                    }
                }
                if (!phones.isClosed()) {
                    phones.close();
                }
            }
        }
        return phoneResult;
    }


    @Override
    public void onLeftClick() {
        finish();
    }

    @Override
    public void onRightClick() {
        SharedPreferences sp = getBaseContext().getSharedPreferences("user", Context.MODE_PRIVATE);
        String token = sp.getString("token", "");

        String inputName = edit_consignee.getText().toString();
        String inputPhone = edit_phone.getText().toString();
        String choosePutAddress = text_address.getText().toString();
        String inputDetail = edit_detail.getText().toString();
//        String inputCode = edit_code.getText().toString();

        province = choosePutAddress.split("-")[0];
        city = choosePutAddress.split("-")[1];
        district = choosePutAddress.split("-")[2];

        if (inputName.equals("")) {
            Toast.makeText(this, "请输入收货人姓名，不可为空", Toast.LENGTH_SHORT).show();
            return;
        }

        if (inputPhone.equals("")) {
            Toast.makeText(this, "请输入收货人手机号码，不可为空", Toast.LENGTH_SHORT).show();
            return;
        }

        if (choosePutAddress.equals("请选择")) {
            Toast.makeText(this, "请选择收货地址", Toast.LENGTH_SHORT).show();
            return;
        }

        if (inputDetail.equals("")) {
            Toast.makeText(this, "请输入详细地址，不可为空", Toast.LENGTH_SHORT).show();
            return;
        }

//        if (inputCode.equals("")) {
//            Toast.makeText(this, "请输入门牌号，不可为空", Toast.LENGTH_SHORT).show();
//            return;
//        }

        Map<String, Object> map = new HashMap<>();
        map.put("token", token);
        map.put("aid", infoBean.getAid());
        map.put("consignee", inputName);
        map.put("telephone", Base64Util.encodedString("UNO" + inputPhone + "HACHA"));
        map.put("province", province);
        map.put("city", city);
        map.put("county", district);
        map.put("address", inputDetail);
        map.put("type", 2);  //编辑地址
        map.put("doorplate", "");
//        map.put("doorplate", inputCode);
        map.put("addressType", "" + addressType);
        map.put("isDefault", "" + isDefault);
        commit(map);
    }

    @Override
    public void onEditTextClick() {

    }

    private void commit(Map<String, Object> map) {
        showDialog("保存中...");
        Set keys = map.keySet();
        if (keys != null) {
            Iterator iterator = keys.iterator();
            while (iterator.hasNext()) {
                Object key = iterator.next();
                Object value = map.get(key);
                LogUtils.e("--编辑收货地址--" + key, ":" + value + "\n");
            }
        }

        XUtil.Post(Url.ADD_NEW_ADDRESS, map, new MyCallBack<String>() {
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                LogUtils.e("==编辑地址=", result);
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    if (jsonObject.optString("re").equals("1")) {

                        BroadCastReceiverUtil.sendBroadcast(EditAddressActivity.this, Constants.ACTION_UPTATE_CONSIGNEE);
                        finish();
                    }

                    ToastUtils.showToast(EditAddressActivity.this, jsonObject.optString("info"));
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFinished() {
                super.onFinished();
                closeDialog();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                super.onError(ex, isOnCallback);
                ex.printStackTrace();
            }
        });
    }


    @Override
    public void pickValue(String value) {
        text_address.setText(value);
        province = value.split("-")[0];
        city = value.split("-")[1];
        district = value.split("-")[2];
    }
}
